<?php


namespace App\HttpController\Api;

use App\Utility\Pool\RedisPool;
use App\Model\Finance\ErrDec;
use EasySwoole\Http\AbstractInterface\Controller;


class Login extends Controller
{
    public function index()
    {
        //var_dump('in');

        //MessageTask::mytask();

        //OrderTask::SetPage('已提交',QueueType::MESSAGE_SUMBIT_ORDER);
        // TODO: Implement index() method.
        $code = $this->request()->getRequestParam('code');

        $redis = RedisPool::defer();
        $token = json_decode($redis->get($code), true);

        if ($token) {

            //拿完就删
            $redis->delete($code);
            $this->success($token);
            return;
        } else {
            $this->fail(ErrDec::TOKEN_EXP);
            return;
        }

    }

    protected function writeJson($statusCode = 200, $msg = null, $result = null)
    {
        if (!$this->response()->isEndResponse()) {
            $data = array(
                "code" => $statusCode,
                "data" => $result,
                "msg" => $msg
            );

            $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
            $this->response()->withStatus($statusCode);

            return true;
        } else {

            return false;
        }
    }

    protected function success($result)
    {
        $this->writeJson(200, 'SUCCESS', $result);

    }

    protected function fail($result)
    {
        $this->writeJson($result[0], $result[1]);
    }


}